﻿using Apache.NMS;
using LD.Host;
using System;
using System.Threading;
using IMessage = Apache.NMS.IMessage;

namespace LD.MES
{
    public class ActiveMQHelper
    {
        private string urlStr = (string)Cache.GetCache(CONST.SHARP_MESURL); //AppSettingHelper.GetConfigValue("mesurl");// "tcp://172.30.96.27:61616";
        protected static AutoResetEvent semaphore = new AutoResetEvent(false);
        protected static ITextMessage message = null;
        protected static TimeSpan receiveTimeout = TimeSpan.FromSeconds(10);
        private string mGuiId;
        private static IConnectionFactory factory;

        public ActiveMQHelper()
        {
            if (factory == null)
                factory = new NMSConnectionFactory(urlStr);
        }
        public string Send(string sendMsg, string machineId, bool isReply)
        {
            //Uri connecturi = new Uri(urlStr);
            try
            {
                using (IConnection connection = factory.CreateConnection())
                {
                    using (ISession session = connection.CreateSession())
                    {

                        //session.RequestTimeout = new TimeSpan(2000);
                        IDestination destination1 = session.GetDestination($"queue://WSEC.{machineId}.QUE.RLY");     //回应
                        IDestination destination2 = session.GetDestination($"queue://WSEC.{machineId}.QUE.REV");     //请求

                        using (IMessageConsumer consumer = session.CreateConsumer(destination1))
                        {
                            using (IMessageProducer producer = session.CreateProducer(destination2))
                            {
                                //producer.RequestTimeout = new TimeSpan(2000);
                                connection.Start();
                                producer.DeliveryMode = MsgDeliveryMode.Persistent;

                                consumer.Listener += new MessageListener(OnMessage);

                                // Send a message
                                ITextMessage request = session.CreateTextMessage(sendMsg);
                                mGuiId = Guid.NewGuid().ToString("N");
                                request.NMSCorrelationID = mGuiId;

                                request.NMSReplyTo = destination1;
                                producer.Send(request);

                                if (!isReply) return string.Empty;

                                // Wait for the message
                                semaphore.WaitOne((int)receiveTimeout.TotalMilliseconds, true);
                                if (message == null)
                                {
                                    Console.WriteLine("No message received!");
                                    throw new Exception("MES无消息回应");
                                }

                                Console.WriteLine("Received message with ID:   " + message.NMSMessageId);
                                Console.WriteLine("Received message with text: " + message.Text);
                                return message.Text;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log4.Error(ex);
                return string.Empty;
            }
        }
        protected void OnMessage(IMessage receivedMsg)
        {
            message = (ITextMessage)receivedMsg;
            Console.WriteLine(receivedMsg.NMSCorrelationID);

            if (!receivedMsg.NMSCorrelationID.Equals(mGuiId)) throw new Exception("回应的消息ID与发送ID不一致"); ;

            Console.WriteLine(message.Text);
            semaphore.Set();
        }
    }
}
